package com.fiveGroup.config;


import com.fiveGroup.ceptor.AuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 1.标注为配置类，注入IOC容器
 * 2.实现一个webMvcConfig
 * 2.1 可以配置跨域策略
 * 2.2可以添加拦截器
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    AuthInterceptor authInterceptor;
    List<String> whiteList = List.of("/api/user/login", "/api/user/register", "/api/captcha/**");

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 允许所有路径的请求
        registry.addMapping("/**")
                // 允许所有来源的请求
                .allowedOriginPatterns("*")
                // 允许所有HTTP方法（GET, POST, PUT, DELETE等）
                .allowedMethods("*")
                .allowedHeaders("*")//允许所有头
                // 允许携带凭证（如 Cookie, Authorization Header）
                .allowCredentials(true)
                // 设置预检请求（Pre-flight request）的缓存时间，单位为秒
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册拦截器并且添加拦截规则
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(whiteList);
    }
    //配置静态资源解析器的位置
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String physicalPath = "D:\\删除实验\\avatars\\";
        registry.addResourceHandler("/avatar/**")
                .addResourceLocations("file:" + physicalPath);
        //静态资源路径，不要包含、api/**
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}

